<template>
  <div class="page-mobile_withdrawal">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      :title="type == 'area-agent' ? '代理提现' : '分销提现'"
    ></white-header>
    <div class="withdrawal-type">
      <div class="type-title">提现方式</div>
      <div class="select-type" @click="showPicker = true">
        <div class="left" v-if="withdrawalType === 0">
          <img src="/img/mobile/account_menus_balance.png" alt="" />
          <div>余额</div>
        </div>
        <div class="left" v-if="withdrawalType === 2">
          <img src="/img/mobile/member_payment_alipay.png" alt="" />
          <div>支付宝</div>
        </div>
        <div class="left" v-if="withdrawalType === 3">
          <img src="/img/mobile/account_menus_balance.png" alt="" />
          <div>银行卡</div>
        </div>
        <img class="right" src="/img/mobile/right-icon.png" alt="" />
      </div>
    </div>
    <div class="account" v-if="[2, 3].includes(withdrawalType)">
      <div class="account-item" style="border-bottom:1px solid #ededf1;">
        <div class="account-left">
          <span style="color:#5c98ff;margin-right:.1rem;">*</span>收款人
        </div>
        <div class="account-right">
          <input
            class="input-box"
            type="text"
            v-model="payee"
            placeholder="请输入收款人姓名"
          />
        </div>
      </div>
      <div class="account-item">
        <div class="account-left">
          <span style="color:#5c98ff;margin-right:.1rem;">*</span>收款账号
        </div>
        <div class="account-right">
          <input
            class="input-box"
            type="text"
            v-model="paymentAccount"
            placeholder="请输入收款人账号"
          />
        </div>
      </div>
    </div>
    <div class="account" v-if="[3].includes(withdrawalType)">
      <div class="account-item" style="border-bottom:1px solid #ededf1;">
        <div class="account-left">
          <span style="color:#5c98ff;margin-right:.1rem;">*</span>收款银行
        </div>
        <div class="account-right">
          <input
            class="input-box"
            type="text"
            v-model="bank"
            placeholder="请输入收款银行"
          />
        </div>
      </div>
      <div class="account-item" style="border-bottom:1px solid #ededf1;">
        <div class="account-left">
          <span style="color:#5c98ff;margin-right:.1rem;">*</span>银行支行
        </div>
        <div class="account-right">
          <input
            class="input-box"
            type="text"
            v-model="subBank"
            placeholder="请输入收款银行支行"
          />
        </div>
      </div>
    </div>
    <div class="withdrawal-money">
      <div class="money-title">提现方式</div>
      <div class="money-box">
        <div class="money-left">
          ￥
        </div>
        <div class="money-right">
          <input
            class="input-box"
            type="text"
            v-model="withdrawalMoney"
            placeholder="请输入金额"
          />
        </div>
      </div>
      <div class="money-tips" v-if="!type">
        当前账户可提现余额&nbsp;
        <span v-if="type == 'area-agent'">{{
          my_profile.profit ? my_profile.profit.toFixed(2) : "0.00"
        }}</span>
        <span v-else>{{
          distribution_info.profit
            ? (
                distribution_info.profit - distribution_info.freezeMoney
              ).toFixed(2)
            : "0.00"
        }}</span
        >&nbsp;元<span class="all-money" @click="allWithdrawalHandle"
          >全部提现</span
        >
      </div>
      <div class="withdrawal-btn" @touchstart="onSubmit">提现</div>
      <div class="withdrawal-tips">
        <span style="color:#5c98ff;margin-right:.1rem;">*</span>注意事项:
        {{
          type == "area-agent" ? "代理" : "分销"
        }}提现需交由管理员审批，请耐心等待
      </div>
    </div>
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
import {
  getDistributionInfo,
  toWithdrawal,
  areaAgentWithdrawal,
  getOwnProfit,
  saveTeamProfit
} from "~/api/distribution";
import { mapState, mapActions, mapMutations } from "vuex";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
export default {
  components: {
    WhiteHeader
  },
  scrollToTop: true,
  data() {
    const _this = this;
    return {
      distribution_info: {},
      withdrawalMoney: "",
      value: "",
      withdrawalType: 2,
      payee: "",
      paymentAccount: "",
      bank: "",
      subBank: "",
      columns: [
        { text: _this.$t("locale.mobile.withdrawak.t10"), label: 0 },
        { text: _this.$t("locale.mobile.withdrawak.t11"), label: 2 },
        { text: "银行卡提现", label: 3 }
      ],
      showPicker: false,
      my_profile: {} //区域代理收益
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      is_loading(state) {
        return state.is_loading;
      }
    }),
    type() {
      return this.$route.query.type;
    }
  },
  watch: {},
  activated() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
    this.getData();
    this.getDistributionInfo();
    this.getOwnProfit();
  },
  deactivated() {
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
  },
  destroyed() {
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
  },
  created() {
    // if (this.actived) {
    //   this.active = this.actived;
    // } else {
    //   this.active = "notification";
    //   this.handleChange("notification");
    // }

    this.getData();
    this.getDistributionInfo();
    this.getOwnProfit();
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  },
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    allWithdrawalHandle() {
      if (this.type == "area-agent") {
        this.withdrawalMoney = this.my_profile.profit.toFixed(2);
      } else {
        this.withdrawalMoney = (
          this.distribution_info.profit - this.distribution_info.freezeMoney
        ).toFixed(2);
      }
    },
    onConfirm(value) {
      this.value = value.text;
      this.withdrawalType = value.label;
      if (this.withdrawalType * 1 == 0) {
        this.paymentAccount = "";
        this.payee = "";
      }
      this.showPicker = false;
    },
    async getOwnProfit() {
      let result = await getOwnProfit({ userId: this.user_info.id });
      console.log("获取我的收益:", result);
      if (result && result.data && result.data.code == 200) {
        const { rows } = result.data.data;
        if (rows.length > 0) {
          this.my_profile = rows[0];
        }
      } else {
        this.$toast("获取失败！");
      }
    },
    async onSubmit(values) {
      if (this.withdrawalType * 1 == 2) {
        if (!this.payee) {
          this.$toast({
            message: "请输入收款人"
          });
          return false;
        }
        if (!this.paymentAccount) {
          this.$toast({
            message: "请输入收款账号"
          });
          return false;
        }
      }
      if (this.withdrawalType * 1 == 3) {
        if (!this.payee) {
          this.$toast({
            message: "请输入收款人"
          });
          return false;
        }
        if (!this.paymentAccount) {
          this.$toast({
            message: "请输入收款账号"
          });
          return false;
        }
        if (!this.bank) {
          this.$toast({
            message: "请输入收款银行"
          });
          return false;
        }
        if (!this.subBank) {
          this.$toast({
            message: "请输入收款银行支行"
          });
          return false;
        }
      }
      const { bank, subBank } = this;
      if (!this.withdrawalMoney) {
        this.$toast({
          message: "请输入提现金额"
        });
        return false;
      }
      let params = {
        withdrawalMoney: +this.withdrawalMoney,
        withdrawalType: +this.withdrawalType,
        payee: this.payee
          ? this.payee
          : this.$t("locale.mobile.withdrawak.t12"),
        paymentAccount: this.paymentAccount
          ? this.paymentAccount
          : this.$t("locale.mobile.withdrawak.t12"),
        userId: this.user_info.id
      };
      console.log(params);
      //区域代理提现
      if (this.type == "area-agent") {
        console.log(
          "————————————————————————————区域代理提现————————————————————————————"
        );
        params = {
          cashType: params.withdrawalType,
          receiver: params.payee,
          receiveAccount: params.paymentAccount,
          userId: params.userId,
          amount: params.withdrawalMoney,
          bank,
          subBank
        };
        let result = await areaAgentWithdrawal(params);
        if (result && result.data && result.data.code == 200) {
          this.$toast.success({
            message: this.$t("locale.mobile.withdrawak.t13"),
            duration: 3000
          });
          this.initState();
        } else {
          if (result && result.data && result.data.code == 204) {
            const { limitAmount } = result.data.data;
            this.$toast("提现金额小于最低可提现金额（" + limitAmount + "元）");
          } else if (result && result.data && result.data.code == 500) {
            this.$toast("当前没有足够的分润余额提现哦");
          } else {
            this.$toast.fail({
              message: this.$t("locale.mobile.withdrawak.t14"),
              duration: 3000
            });
          }
        }
      } else if (this.type == "team-distribution") {
        console.log(
          "————————————————————————————团队分销提现————————————————————————————"
        );
        params = {
          cashType: params.withdrawalType,
          receiver: params.payee,
          receiveAccount: params.paymentAccount,
          userId: params.userId,
          amount: params.withdrawalMoney,
          bank,
          subBank
        };
        let result = await saveTeamProfit(params);
        console.log(":result:", result);
        if (result && result.data && result.data.code == 200) {
          this.$toast.success({
            message: this.$t("locale.mobile.withdrawak.t13"),
            duration: 3000
          });
          this.initState();
        } else {
          if (result && result.data && result.data.code == 204) {
            const { limitAmount } = result.data.data;
            this.$toast("提现金额小于最低可提现金额（" + limitAmount + "元）");
          } else if (result && result.data && result.data.code == 500) {
            this.$toast("当前没有足够的分润余额提现哦");
          } else {
            this.$toast.fail({
              message: this.$t("locale.mobile.withdrawak.t14"),
              duration: 3000
            });
          }
        }
      } else {
        console.log(
          "————————————————————————————三级代理提现————————————————————————————"
        );
        params = {
          ...params,
          bank,
          subBank
        };
        if (
          (
            this.distribution_info.profit - this.distribution_info.freezeMoney
          ).toFixed(2) -
            (+this.withdrawalMoney).toFixed(2) >=
          0
        ) {
          this.is_show_withdrawal_modal = false;
          //三级分销提现
          toWithdrawal(params)
            .then(res => {
              if (res && res.data && res.data.code == 200) {
                this.getDistributionInfo();
                this.$toast.success({
                  message: this.$t("locale.mobile.withdrawak.t13"),
                  duration: 3000
                });
                this.initState();
              } else {
                this.$toast.fail({
                  message: res.data.msg,
                  duration: 3000
                });
              }
            })
            .catch(err => {
              this.$toast.fail({
                message: this.$t("locale.mobile.withdrawak.t14"),
                duration: 3000
              });
            });
        } else {
          this.$toast.fail({
            message: this.$t("locale.mobile.withdrawak.t15"),
            duration: 3000
          });
        }
      }
      console.log("submit", values);
    },
    initState() {
      this.withdrawalMoney = "";
      this.value = "";
      // this.withdrawalType = 2;
      this.payee = "";
      this.paymentAccount = "";
      this.bank = "";
      this.subBank = "";
    },
    toPath(path) {
      this.$router.push(path);
    },
    // handleChange(name) {
    //   this.$router.replace({
    //     path: "/m/notice",
    //     query: {
    //       actived: name
    //     }
    //   });
    //   this.active = name;
    //   this.page = 1;
    //   this.getData();
    // },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function() {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    },
    pullUp() {
      //   // 滚动条离顶部的距离
      //   let scrollTop =
      //     document.documentElement.scrollTop || document.body.scrollTop;
      //   // 窗口可视区域高度
      //   let clientHeight =
      //     document.documentElement.clientHeight || document.body.clientHeight;
      //   // 滚动区域高度
      //   let scrollHeight =
      //     document.documentElement.scrollHeight || document.body.scrollHeight;
      //   // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      //   if (scrollTop + clientHeight >= scrollHeight) {
      //     console.log("上拉加载");
      //     if (this.total <= this.notice_list.length) {
      //       return;
      //     }
      //     if (this.is_loading) {
      //       return;
      //     }
      //     this.page++;
      //     this.getData("pullup");
      //   }
    },
    eventListener() {
      this.throttle(this.pullUp, 300);
    },
    async getDistributionInfo() {
      this.SET_IS_LOADING(true);
      let params = {
        userId: this.user_info.id
      };
      let result = await getDistributionInfo(params);
      if (result && result.data && result.data.code == 200) {
        this.distribution_info = result.data.data;
        this.SET_IS_LOADING(false);
      } else {
        this.$toast.fail(this.$t("locale.mobile.withdrawak.t16"));
        this.SET_IS_LOADING(false);
      }
    },
    async getData(fetch_type) {
      //   this.SET_IS_LOADING(true);
      //   let result = await getNotice({
      //     sort: "id",
      //     sortType: "desc",
      //     offset: this.pageSize * (this.page - 1),
      //     limit: this.pageSize,
      //     isOpen: 1,
      //     type:
      //       this.active && this.active == "notification"
      //         ? 1
      //         : this.active && this.active == "notice"
      //         ? 2
      //         : 1
      //   });
      //   if (result && result.data.code == 200) {
      //     if (fetch_type == "pullup") {
      //       this.notice_list = [...this.notice_list, ...result.data.data.rows];
      //     } else {
      //       this.notice_list = result.data.data.rows;
      //     }
      //     this.total = result.data.data.total;
      //     this.SET_IS_LOADING(false);
      //   } else {
      //     this.SET_IS_LOADING(false);
      //     this.$toast("获取失败！");
      //   }
      // }
    }
  }
};
</script>

<style lang="scss">
.page-mobile_withdrawal {
  width: 7.2rem;
  min-height: 100vh;
  background-color: #f7f7fa;
  .withdrawal-type {
    // border-top: 1px solid #ededf1;
    width: 7.2rem;
    height: 2.4rem;
    box-sizing: border-box;
    padding: 0.4rem 0.288rem;
    background-color: #ffffff;
    .type-title {
      color: #313233;
      font-weight: bold;
      font-size: 0.3072rem;
    }
    .select-type {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 0.5rem;
      .left {
        display: flex;
        align-items: center;
        color: #313233;
        font-size: 0.34559rem;
        img {
          width: 0.48rem;
          height: 0.48rem;
          display: block;
          margin-right: 0.2rem;
        }
      }
      .right {
        width: 0.2304rem;
        height: 0.2304rem;
        display: block;
      }
    }
  }
  .account {
    box-sizing: border-box;
    padding: 0.288rem;
    width: 7.2rem;
    background-color: #ffffff;
    margin-top: 0.2rem;
    .account-item {
      width: 100%;
      height: 1rem;
      display: flex;
      .account-left {
        width: 30%;
        font-size: 0.288rem;
        font-weight: bold;
        line-height: 1rem;
        color: #313233;
      }
      .account-right {
        width: 70%;
        color: #313233;
        font-size: 0.288rem;
        display: flex;
        align-items: center;
        .input-box {
          border: none;
          width: 100%;
          height: 0.8rem;
          font-size: 0.288rem;
        }
      }
    }
  }
  .withdrawal-money {
    width: 7.2rem;
    // height: 2.4rem;
    box-sizing: border-box;
    padding: 0.4rem 0.288rem;
    background-color: #ffffff;
    margin-top: 0.2rem;
    .money-title {
      color: #313233;
      font-weight: bold;
      font-size: 0.3072rem;
    }
    .money-box {
      width: 100%;
      height: 1rem;
      border-bottom: 1px solid #ededf1;
      display: flex;
      align-items: center;
      .money-left {
        width: 10%;
        font-size: 0.4224rem;
        // height: 1rem;
        color: #313233;
        font-weight: bold;
      }
      .money-right {
        width: 90%;
        // height: 1rem;
        height: 80%;
        .input-box {
          width: 100%;
          height: 100%;
          font-size: 0.3rem;
          border: none;
        }
      }
    }
    .money-tips {
      font-size: 0.2688rem;
      color: #b7babd;
      line-height: 0.5rem;
      .all-money {
        margin-left: 0.2rem;
        color: #5c98ff;
      }
    }
    .withdrawal-btn {
      margin-top: 0.3rem;
      width: 100%;
      height: 0.8448rem;
      background-color: var(--theme-color);
      border-radius: 0.4224rem;
      color: #ffffff;
      text-align: center;
      line-height: 0.8448rem;
      font-weight: bold;
      font-size: 0.3072rem;
    }
    .withdrawal-tips {
      font-size: 0.2688rem;
      line-height: 0.6rem;
    }
  }
}
</style>
